package com.gitee.xmhzzz.component.redisson;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.time.Duration;
import java.util.Objects;

/**
 * 基于资源考虑，目前共用当前应用的同一个RedisProperties
 *
 * @author Hongyu
 */
@Configuration
// @AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedissonConfiguration {

    private Boolean redissonUseLocalHost = false;
    private static final int MIN_CONNECTION_SIZE = 1;
    private static final int MAX_CONNECTION_SIZE = 128;

    private static final String REDIS_SCHEMA = "redis";
    private static final String REDIS_SSL_SCHEMA = "rediss";

    private static final Logger log = LoggerFactory.getLogger(RedissonConfiguration.class);

    @Bean
    @Lazy
    public RedissonClient redissonClient(RedisProperties properties) {

        Config config = new Config();
        config.setLockWatchdogTimeout(Duration.ofSeconds(10).toMillis());

        config.useSingleServer().setSslEnableEndpointIdentification(properties.isSsl());
        // config.useSingleServer().setClientName("DistributedRedisLock");
        if (redissonUseLocalHost) {
            config.useSingleServer().setAddress("redis://localhost:6379");
        } else {
            String address = String.format("%s://%s:%s",
                    properties.isSsl() ? REDIS_SSL_SCHEMA : REDIS_SCHEMA, properties.getHost(), properties.getPort());

          log.info("######## redisson address：{}",address);
            config.useSingleServer().setAddress(address);
            String password = StringUtils.isEmpty(properties.getPassword()) ? null : properties.getPassword();
            config.useSingleServer().setPassword(password);
        }
        config.useSingleServer().setDatabase(properties.getDatabase());
        Duration timeout = properties.getTimeout();
        if (Objects.nonNull(timeout)) {
            config.useSingleServer().setTimeout((int) timeout.toMillis());
        }
        // 考虑到生产可能会暴量，double default value here
        config.useSingleServer().setConnectionPoolSize(MAX_CONNECTION_SIZE);
        config.useSingleServer().setConnectionMinimumIdleSize(MIN_CONNECTION_SIZE);
        return Redisson.create(config);
    }


}
